<template>
  <div class="pacs_main">
    <head-nav :firstTitle="'影像存档'" :subTitle="'存档首页'"></head-nav>
    <div class="main_top">
      <div class="left mr5">
        <div class="bbf5">
          <!--            <img :src="logoSrc" class="w171 h171 mt70">-->
          <div class="w171 h171" style="margin: 43px auto 0">
            <el-image :src="logoSrc" class="w171">
              <div slot="error" class="image-slot w100 h100 position_relative bg_f5">
                <i class="el-icon-picture-outline f30 position_absolute toCenter clr_ccc"></i>
              </div>
            </el-image>
          </div>
          <p class="f18 mt30 mb40">{{ organizationName }}</p>
        </div>
        <div class="pl21 pr21 tl pt36 flex_row space_between">
          <div class>
            <p class="f14">已接入医疗机构</p>
            <span class="f28 clr_1C8BE4">{{ institutionCount }}</span>
          </div>
          <i class="dib w1 h51 bg_ddd"></i>
          <div class>
            <p class="f14">已接入影像设备</p>
            <span class="f28 clr_1C8BE4">{{ modalityCount }}</span>
          </div>
        </div>
      </div>
      <div class="right pl20 pr20">
        <ul class="mt15 h130 bdcd bradius8 row">
          <li>
            <p class="text_nowrap clr_1C8BE4">今日新增影像检查</p>
            <span class="clr_1C8BE4 f28">{{ todayStatistics.total_count }}</span>
          </li>
          <li v-for="(item, index) in todayStatistics.study_counts" :key="index">
            <p>{{ item.modalities_in_study }}</p>
            <span>{{ item.count }}</span>
          </li>
          <li v-if="todayStatistics.study_counts && todayStatistics.study_counts.length === 0"
            style="display: flex; align-items: center;">
            <div>今日暂无新增影像检查</div>
          </li>
        </ul>
        <div class="h40 mt20 todayCheck flex_row space_between">
          <div class="w423 bg_eaf6ff bradius4 lh40 f14">
            <i class="iconfont clr_1C8BE4 f24i ml30 mr10 vam">&#xe68a;</i>
            <span class="clr_1c8be4">今日影像检查已登记数：{{ todayRISCount }}</span>
          </div>
          <div class="w423 bg_eaf6ff bradius4 lh40 f14">
            <i class="iconfont clr_1C8BE4 f24i ml30 mr10 vam">&#xe68b;</i>
            <span class="clr_1c8be4">今日PACS已归档检查数：{{ todayStatistics.pacs_count }}</span>
          </div>
          <div class="w423 bg_fff1f1 bradius4 lh40 f14">
            <a @click.prevent="toMatching" class="ml30 cursor">
              <i class="iconfont clr_ff6f6f f24i mr10 vam">&#xe687;</i>
              <span class="bbt_ff6f6f clr_ff6f6f">今日尚未匹配到影像检查数：{{ todayStatistics.un_match_count }}</span>
            </a>
          </div>
        </div>
        <div class="f18 mt15">策略情况</div>
        <div class="strategy flex_row pt15 f14">
          <div class="strategy_box strategy mr28 w624">
            <div class="pl30 pr36 flex_row space_between lh40">
              <div>
                <img src="../../assets/images/pacs/routeStrategy.png" class="w20 h20 mr10 vam" />
                <span>路由策略</span>
              </div>
              <div>
                <a v-if="!strategyInfo.is_routing_setting" @click.prevent="toStrategyConfig" class="cursor">
                  <i class="iconfont clr_c1 f16i mr10 vam">&#xe680;</i>
                  <span class="clr_1C8BE4 bbt_0a70b0">未设置</span>
                </a>
                <a v-if="strategyInfo.is_routing_setting" @click.prevent="toStrategyConfig" class="cursor">
                  <i class="iconfont clr_1C8BE4 f16i mr10 vam">&#xe681;</i>
                  <span class="clr_1C8BE4 bbt_0a70b0">已设置</span>
                </a>
              </div>
              <div v-if="!strategyInfo.is_routing_running">
                <i class="iconfont clr_ff6f6f f16i mr10 vam">&#xe67e;</i>
                <span>未执行</span>
              </div>
              <div v-if="strategyInfo.is_routing_running">
                <i class="iconfont clr_49b523 f16i mr10 vam">&#xe67e;</i>
                <span>执行中</span>
              </div>
            </div>
            <div class="mt10 mb10 pl30 pr36 flex_row space_between lh40">
              <div>
                <img src="../../assets/images/pacs/nearLineStrategy.png" class="w20 h20 mr10 vam" />
                <span>近线策略</span>
              </div>
              <div>
                <a v-if="!strategyInfo.is_nearline_setting" @click.prevent="toSetSaveStrategy" class="cursor">
                  <i class="iconfont clr_c1 f16i mr10 vam">&#xe680;</i>
                  <span class="clr_1C8BE4 bbt_0a70b0">未设置</span>
                </a>
                <a v-if="strategyInfo.is_nearline_setting" @click.prevent="toSetSaveStrategy" class="cursor">
                  <i class="iconfont clr_1C8BE4 f16i mr10 vam">&#xe681;</i>
                  <span class="clr_1C8BE4 bbt_0a70b0">已设置</span>
                </a>
              </div>
              <div v-if="!strategyInfo.is_nearline_running">
                <i class="iconfont clr_ff6f6f f16i mr10 vam">&#xe67e;</i>
                <span>未执行</span>
              </div>
              <div v-if="strategyInfo.is_nearline_running">
                <i class="iconfont clr_49b523 f16i mr10 vam">&#xe67e;</i>
                <span>执行中</span>
              </div>
            </div>
            <div class="pl30 pr36 flex_row space_between lh40">
              <div>
                <img src="../../assets/images/pacs/backupStrategy.png" class="w20 h14 mr10 vam" />
                <span>压缩策略</span>
              </div>
              <div>
                <a v-if="!strategyInfo.is_compress_setting" @click.prevent="toSetSaveStrategy" class="cursor">
                  <i class="iconfont clr_c1 f16i mr10 vam">&#xe680;</i>
                  <span class="clr_1C8BE4 bbt_0a70b0">未设置</span>
                </a>
                <a v-if="strategyInfo.is_compress_setting" @click.prevent="toSetSaveStrategy" class="cursor">
                  <i class="iconfont clr_1C8BE4 f16i mr10 vam">&#xe681;</i>
                  <span class="clr_1C8BE4 bbt_0a70b0">已设置</span>
                </a>
              </div>
              <div v-if="!strategyInfo.isCompressRunning">
                <i class="iconfont clr_ff6f6f f16i mr10 vam">&#xe67e;</i>
                <span>未执行</span>
              </div>
              <div v-if="strategyInfo.isCompressRunning">
                <i class="iconfont clr_49b523 f16i mr10 vam">&#xe67e;</i>
                <span>执行中</span>
              </div>
            </div>
          </div>
          <div class="strategy_box col">
            <div class="pl30 pr36 flex_row space_between lh40">
              <div>
                <img src="../../assets/images/pacs/deleteStrategy.png" class="w20 h20 mr10 vam" />
                <span>删除策略</span>
              </div>
              <div>
                <a v-if="!strategyInfo.is_offline_setting" @click.prevent="toSetSaveStrategy" class="cursor">
                  <i class="iconfont clr_c1 f16i mr10 vam">&#xe680;</i>
                  <span class="clr_1C8BE4 bbt_0a70b0">未设置</span>
                </a>
                <a v-if="strategyInfo.is_offline_setting" @click.prevent="toSetSaveStrategy" class="cursor">
                  <i class="iconfont clr_1C8BE4 f16i mr10 vam">&#xe681;</i>
                  <span class="clr_1C8BE4 bbt_0a70b0">已设置</span>
                </a>
              </div>
              <div v-if="!strategyInfo.is_offline_running">
                <i class="iconfont clr_ff6f6f f16i mr10 vam">&#xe67e;</i>
                <span>未执行</span>
              </div>
              <div v-if="strategyInfo.is_offline_running">
                <i class="iconfont clr_49b523 f16i mr10 vam">&#xe67e;</i>
                <span>执行中</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class style="margin-top: 5px; width: 100%; height: 410px;">
      <div class="clear_fixed" style=" margin-top: 5px">
        <div class="bgf w470 h410 fl mr5 flex_position flex_column">
          <div v-if="saveDeviceList.length > 0">
            <system-memory boxWidth="w370" boxHeight="h370" boxTitle="系统存储使用" :boxText1="allText"
              boxText1Font="22px Microsoft YaHei"
              :boxValue="allUsed && allTotal && parseFloat(allUsed) / parseFloat(allTotal) || 0"></system-memory>
          </div>
        </div>
        <div class="row flex_center bgf of_auto h410 flex_wrap">
          <!-- flex_wrap -->
          <div v-for="item in saveDeviceList" :key="item.id">
                <cloud-memory boxWidth="w236" boxHeight="h236" :colorStart="item.colorStart" :colorStop="item.colorStop"
                  :totalSpace="item.total_space" :currentSpace="item.current_space"
                  :cloudName="item.device_name"></cloud-memory>
              </div>
              <div class="no-data" v-if="saveDeviceList.length === 0">
                <img src="../../assets/images/common/NoData.png" alt="">
                <div>暂无数据</div>
              </div>
              <!-- <div class="top_title">
                在线容量、近线容量
              </div> -->

         <!-- <div v-if="onlineDeviceList.length>0 || nearDeviceList.length>0">
          <div class="left h100" v-if="onlineDeviceList.length>0">
            <div>在线设备</div>
            <div class="flex_wrap  row flex_center">
              <div v-for="item in onlineDeviceList" :key="item.id">
                <cloud-memory boxWidth="w236" boxHeight="h236" :colorStart="item.colorStart" :colorStop="item.colorStop"
                  :totalSpace="item.total_space" :currentSpace="item.current_space"
                  :cloudName="item.device_name"></cloud-memory>
              </div>
              <div class="no-data" v-if="onlineDeviceList.length === 0">
                <img src="../../assets/images/common/NoData.png" alt="">
                <div>暂无数据</div>
              </div>
            </div>
          </div>

          <div class="right h100" v-if="nearDeviceList.length>0">
            <div>近线设备</div>
            <div class="flex_wrap  row flex_center">

              <div v-for="item in nearDeviceList" :key="item.id">
                <cloud-memory boxWidth="w236" boxHeight="h236" :colorStart="item.colorStart" :colorStop="item.colorStop"
                  :totalSpace="item.total_space" :currentSpace="item.current_space"
                  :cloudName="item.device_name"></cloud-memory>
              </div>
              <div class="no-data" v-if="nearDeviceList.length === 0">
                <img src="../../assets/images/common/NoData.png" alt="">
                <div>暂无数据</div>
              </div>
            </div>
          </div>
         </div>
         <div class="no-data" v-else>
                <img src="../../assets/images/common/NoData.png" alt="">
                <div>暂无数据</div>
              </div>  -->

        </div>
      </div>
    </div>
    <transition name="slide-fade">
      <el-alert v-if="checkTimeErrorAlertShow" type="warning" description="系统内存在检查时间错误数据！" close-text="查看详情" show-icon
        @close="checkTimeErrorAlertClose"
        style="width: 440px;height: 50px;position: fixed;z-index: 10000;right: 0;top:170px"></el-alert>
    </transition>
    <transition name="slide-fade">
      <div v-if="checkTimeErrorAlertShow" class="dataCheckTip w580 h50 lh50 alert_bshadow bgf bradius4"
        style="position: fixed;right: 0;top: 240px">
        <span class="f14 ml40 mr10">数据校对进度</span>
        <el-progress :percentage="dataCheckPercentage" :format="dataCheckFormat" class="w225 dib"></el-progress>
        <div class="dib f12 clr_999">
          <span>{{ dataCheckCurrent }}</span>/
          <span>{{ dataCheckAll }}</span>
        </div>
        <el-link type="danger" :underline="false" class="f12 ml40">已发现错误数 1</el-link>
      </div>
    </transition>
    <!-- <el-button @click="checkTimeErrorAlertShow = !checkTimeErrorAlertShow">
      toggle
    </el-button>-->
  </div>
</template>

<script>
import HeadNav from "@/components/common/HeadNav"; // 头部导航
import SystemMemory from "@/components/pacs/systemMemory"; // 水球
import CloudMemory from "@/components/pacs/cloudMemory"; // 环形
import moment from "moment";
import { mapGetters } from "vuex";

export default {
  name: "home",
  data() {
    return {
      organizationName: "",
      institutionCount: 0,
      modalityCount: 0,
      todayStatistics: {},
      todayRISCount: "",
      strategyInfo: {},
      checkTimeErrorAlertShow: false, // 系统内存在检查时间错误数据
      imgSendPercentage: 0,
      dataCheckCurrent: 0,
      dataCheckAll: 4000,
      apiUrl: "",
      logoSrc: "",
      baseUrl: "",
      saveDeviceList: [],
      nearDeviceList: [],
      onlineDeviceList: [],
      colorArr: [
        { colorStart: '#8D98F0', colorStop: '#6F88E0' },
        { colorStart: '#88D489', colorStop: '#7FD4B2' },
        { colorStart: '#FFD071', colorStop: '#F68C6C' },
        { colorStart: '#F0E48D', colorStop: '#A8E06F' },
        { colorStart: '#D276FF', colorStop: '#BD7FD4' },
        { colorStart: '#EFDA00', colorStop: '#F6E56C' },
      ],
      allText: null,
      allUsed: null,
      allTotal: null
    };
  },
  computed: {
    ...mapGetters(['loginInfo']),
    dataCheckPercentage() {
      return Math.floor((this.dataCheckCurrent / this.dataCheckAll) * 100);
    },
  },
  provide() {
    return {
      device: this,
    };
  },
  methods: {
    async getSaveDeviceList() {
      const res = await this.$pacsApi.pacsApi.getSaveDeviceList();
      const { code, data } = res;
      if (code === 0) {
        let colorNum = 0;
        let newArr = [];
        data.forEach(ele => {
          if (ele.current_space && ele.total_space) {
            ele.colorStart = this.colorArr[colorNum].colorStart;
            ele.colorStop = this.colorArr[colorNum].colorStop;
            newArr.push(ele);
            if (colorNum < this.colorArr.length) {
              colorNum++;
            } else {
              colorNum = 0;
            }
          }
        });
        
        this.saveDeviceList = newArr;
        this.dataFormat();
      }
    },
    dataFormat() {
      let num1 = [];
      let num2 = [];
      this.saveDeviceList.forEach(item => {
        if (item.device_type == 0) {
          //在线
          this.onlineDeviceList.push(item)
        }else if (item.device_type == 1) {
          //近线
          this.nearDeviceList.push(item)
        }
        
        num1.push(this.unitChange(item.current_space));
        num2.push(this.unitChange(item.total_space));
      });

      num1.forEach(ele => {
        this.allUsed += ele;
      });
      num2.forEach(ele => {
        this.allTotal += ele;
      });
      this.allText = this.diskSize(this.allUsed) + '/' + this.diskSize(this.allTotal);
      // this.allVal = this.allUsed / this.allTotal;
    },
    unitChange(str) {
      if (str == null) { return 0; }
      const k = 1024;
      let type = str.slice(str.length - 1);
      let num = str.slice(0, str.length - 1);
      const sizeStr = ['B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']; //容量单位
      for (let i = 0; i < sizeStr.length; i++) {
        const size = sizeStr[i];
        if (type === size) {
          return Math.pow(k, i) * num;
        }
      }
    },
    diskSize(num) {
      if (num === 0) return '0B';
      const k = 1024;
      const sizeStr = ['B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'];
      let i = 0;
      for (let l = 0; l < sizeStr.length; l++) {
        if (num / Math.pow(k, l) < 1) {
          break;
        }
        i = l;
      }
      return (num / Math.pow(k, i)).toFixed(2) + sizeStr[i];
    },
    checkTimeErrorAlertClose() {
      this.checkTimeErrorAlertShow = false;
    },
    imgSendFormat(percentage) {
      return `${percentage}/100`;
      // return percentage === 100 ? '满' : `${percentage}%`;
    },
    dataCheckFormat(percentage) {
      return `${percentage}%`;
    },
    toMatching() {
      this.$router.push({
        path: this.baseUrl + "/IMGLIST/matching",
        query: { checktime: "today", group: this.$store.getters.group },
      });
    },
    toStrategyConfig() {
      this.$router.push({
        name: "RoutingStrategyConfig",
        query: { activeName: "5", group: this.$store.getters.group },
      });
    },
    toSetSaveStrategy() {
      this.$router.push({
        name: "MemoryDeviceConfig",
        query: { SetSaveStrategyShow: "open", group: this.$store.getters.group },
      });
    },
    async imgStatistics() {
      let res = await this.$pacsApi.pacsApi.imgStatistics();
      let { code, data } = res;
      if (code === 0) {
        this.todayStatistics = data;
      }
    },
    async getImgDeviceAndInstitutionNum() {
      let res = await this.$pacsApi.pacsApi.getImgDeviceAndInstitutionNum();
      let { code, data } = res;
      if (code === 0) {
        this.institutionCount = data.institution_count;
        this.modalityCount = data.modality_count;
      }
    },
    async getStrategyInfo() {
      let res = await this.$pacsApi.pacsApi.getStrategyInfo();
      let { code, data } = res;
      if (code === 0) {
        this.strategyInfo = data;
      }
    },
    async getCompleteDetails() {
      const res = await this.$pacsApi.pacsApi.getCompleteDetails();
      const { code, data } = res;
      if (code === 0) {
        this.organizationName = data.platform_info.name;
      }
    },
    async getLogo() {
      let res = await this.$pacsApi.pacsApi.getLogo();
      let { code, data } = res;
      if (code === 0) {
        // this.organizationName = data.name;
        // if (data.logo === "0") {
        //   // 使用默认机构logo
        //   this.logoSrc = require("../../assets/images/pacs/defaultInstitution.png");
        //   return;
        // }
        // let fileRes = await this.$pacsApi.pacsApi.getLogoPic(data.logo)
        // let blobData = new Blob([fileRes])
        // this.logoSrc = configUrl.apiUrl + `/api-operate/medias/${data.logo}`
        // let picRes = await this.$pacsApi.pacsApi.getLogoPic(data.logo)

        const tid = JSON.parse(this.loginInfo)?.profile?.tenancy_id;
        // let picRes = await this.$pacsApi.pacsApi.getTenanciesLogo(
        //   data.logo,
        //   tid
        // );
        let picRes = await this.$pacsApi.pacsApi.getPortalsLog(tid).catch(err => {
          // console.log(err);
          this.logoSrc = require("../../assets/images/pacs/defaultInstitution.png");
        });
        if (this.logoSrc) {
          return
        }
        let blobData = new Blob([picRes]);
        this.logoSrc = URL.createObjectURL(blobData);
      } else {
        this.logoSrc = require("../../assets/images/pacs/defaultInstitution.png");
      }
    },
    async getRISCount() {
      let todayBegin = moment().format("yyyy-MM-DD") + " 00:00:00";
      let todayEnd = moment().format("yyyy-MM-DD") + " 23:59:59";
      let params = { BeginDate: todayBegin, EndDate: todayEnd };
      // 如果为dept, 入参加入systemid
      if (this.$store.getters.group === "dept") {
        params.systemid = this.$store.getters.systemid;
      }
      let res = await this.$pacsApi.pacsApi.getRISCount(params);
      let { code, data } = res;
      if (code === 0) {
        this.todayRISCount = data;
      }
    },
  },
  mounted() {
    this.baseUrl = process.env.NODE_ENV === "development" ? "" : "/paservice";
    this.imgStatistics();
    this.getImgDeviceAndInstitutionNum();
    this.getStrategyInfo();
    this.getLogo();
    this.getCompleteDetails();
    this.getRISCount();
    this.getSaveDeviceList();
    const timeId = setInterval(() => {
      if (this.imgSendPercentage === 100) {
        clearInterval(timeId);
      } else {
        this.imgSendPercentage++;
      }
    }, 100);
    const timeId1 = setInterval(() => {
      if (this.dataCheckCurrent === this.dataCheckAll) {
        clearInterval(timeId1);
      } else {
        this.dataCheckCurrent++;
      }
    }, 10);
  },
  components: {
    SystemMemory,
    CloudMemory,
    HeadNav
  },
  beforeRouteEnter(to, from, next) {
    document.querySelector("html").style.backgroundColor = "#F5F5F5";
    document.querySelector("body").style.backgroundColor = "#F5F5F5";
    next();
  },
  beforeRouteLeave(to, from, next) {
    document.querySelector("html").style.backgroundColor = "#FFF";
    document.querySelector("body").style.backgroundColor = "#FFF";
    next();
  },
};
</script>

<style lang="less" scoped>

.of_auto_y{
  overflow-y: auto;
}
.f16i {
  font-size: 16px !important;
}

.f24i {
  font-size: 24px !important;
}

.el-alert.el-alert--warning.is-light {
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  border-radius: 4px;
}

/deep/.el-alert .el-alert__description {
  font-size: 14px;
  margin-top: 0;
}

/deep/.el-alert.is-light .el-alert__closebtn {
  top: 15px !important;
}

.slide-fade-enter-active,
.slide-fade-leave-active {
  transition: all 0.3s;
}

.slide-fade-enter,
.slide-fade-leave-to

/* .slide-fade-leave-active for below version 2.1.8 */
  {
  transform: translateX(460px);
  opacity: 0;
}

/deep/.el-progress-bar__outer {
  width: 170px;
  height: 10px !important;
  margin-right: 0;
}

.imgSendTip {
  /deep/.el-progress__text {
    font-size: 12px !important;
    margin-left: 0;
    color: #999999;
  }
}

.dataCheckTip {
  /deep/.el-progress__text {
    font-size: 12px !important;
    margin-left: 10px;
    color: #0a70b0;
  }
}

.no-data {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

ul>li {
  text-align: center;
}
</style>
